package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.upload.config.OssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 *
 */
@Service
public class UploadService {

    @Autowired
    private OssProperties ossProps;

    @Autowired
    private OSS ossClient;

    public String uploadImage(MultipartFile file) {
        //需求：把上传的图片保存在本地nginx服务器

        //判断文件是否为图片格式
        //思路：判断该文件是否可以以图片流的格式读取出来，如果可以，代表它是图片，不可以，不是图片
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());

            if (image == null) {
                //该文件不是图片
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        //1.定义随机的文件名称，防止重名
        //1.1 获取原名
        String originalFilename = file.getOriginalFilename();
        //1.2 获取后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".")); // .jpg
        //1.3 使用UUID作为文件名称
        String fileName = UUID.randomUUID().toString() + extName;


        //2.保存文件
        try {
            file.transferTo(new File(LyConstants.IMAGE_PATH + fileName));

            return LyConstants.IMAGE_URL + fileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

    }

    public Map<String, Object> getOssSignature() {
        try {
            long expireTime = ossProps.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            //设置文件上传大小
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, ossProps.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossProps.getDir());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<String, Object>();
            respMap.put("accessId", ossProps.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", ossProps.getDir());
            respMap.put("host", ossProps.getHost());
            respMap.put("expire", expireEndTime);

            return respMap;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_SIGN);
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 上传图片到阿里云
     */
    public String uploadImageAliyun(MultipartFile file) {
        //判断文件是否为图片格式
        //思路：判断该文件是否可以以图片流的格式读取出来，如果可以，代表它是图片，不可以，不是图片
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());

            if(image==null){
                //该文件不是图片
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        //1.定义随机的文件名称，防止重名
        //1.1 获取原名
        String originalFilename = file.getOriginalFilename();
        //1.2 获取后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".")); // .jpg
        //1.3 使用UUID作为文件名称
        String fileName = UUID.randomUUID().toString()+extName;


        //2.保存文件
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");
            ossClient.putObject("ly-upload-lijiaoqiserver", fileName, file.getInputStream(),objectMetadata);

            return LyConstants.ALIYUN_IMAGE_URL+fileName;

        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

    }
}
